﻿using System;
using System.Threading;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Threading;

namespace Report
{
    public class PrintMain
    {
        private delegate void DoPrintMethod(PrintDialog pdlg, DocumentPaginator paginator);
        private delegate void EnableButtonMethod();
        private Timer m_timerToEnableButton;

        private void DoPrint(PrintDialog pdlg, DocumentPaginator paginator)
        {
            pdlg.PrintDocument(paginator, this.Title);
        }
        public string XamlName { get; set; }
        public Object UserData { get; set; }
        public IDocumentRenderer Renderer { get; set; }

        public string Title { get; set; }
        public PrintType PrintType { get; set; }

        public PrintMain(string xamlName, object data, IDocumentRenderer renderer, string title, PrintType printType = PrintType.PreView)
        {
            this.XamlName = xamlName;
            this.UserData = data;
            this.Renderer = renderer;
            this.Title = title;
            PrintType = printType;

        }

        public void Go()
        {
            switch (this.PrintType)
            {
                case PrintType.Direct:
                    PrintDirect();
                    break;
                case PrintType.PreView:
                    PrintPreview();
                    break;
                case PrintType.PrintSet:
                    PrintSet();
                    break;
                default:
                    PrintPreview();
                    break;
            }

        }

        private void PrintDirect()
        {
            PrintDialog pdlg = new PrintDialog();
            FlowDocument doc = PrintPreviewWindow.LoadDocumentAndRender(this.XamlName, this.UserData, Renderer);
            System.Windows.Application.Current.Dispatcher.BeginInvoke(new DoPrintMethod(DoPrint), DispatcherPriority.ApplicationIdle, pdlg, ((IDocumentPaginatorSource)doc).DocumentPaginator);
            m_timerToEnableButton = new Timer(TestTimerCallback, null, 3000, Timeout.Infinite);
        }
        private void PrintPreview()
        {
            PrintPreviewWindow previewWnd = new PrintPreviewWindow(this.XamlName, this.UserData, this.Renderer);
            previewWnd.ShowInTaskbar = false;
            previewWnd.ShowDialog();
        }
        private void PrintSet()
        {
            PrintDialog pdlg = new PrintDialog();
            if (pdlg.ShowDialog() == true)
            {
                FlowDocument doc = PrintPreviewWindow.LoadDocumentAndRender(this.XamlName, this.UserData, this.Renderer);
                System.Windows.Application.Current.Dispatcher.BeginInvoke(new DoPrintMethod(DoPrint), DispatcherPriority.ApplicationIdle, pdlg, ((IDocumentPaginatorSource)doc).DocumentPaginator);
            }
        }
        public void TestTimerCallback(Object state)
        {
            m_timerToEnableButton.Dispose();
        }
    }
}
